<template>
    <div>
        <div class="block">

            <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
            <el-button v-if="draggable" @click="batchSave">拖拽完保存</el-button>
            <el-button type="danger" @click="batchDelete">批量删除</el-button>

            <el-input
                placeholder="输入关键字进行过滤"
                v-model="filterText">
            </el-input>

            <el-tree
            :data="data"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            :default-expanded-keys="expandedKey"
            :default-expand-all="false"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            :draggable="draggable"
            :allow-drop="allowDrop"
            @node-drop="handleDrop"
            ref="tree">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ node.label }}</span>
                    <span>
                    <el-button
                        v-if="node.level == 1"
                        type="text"
                        size="mini"
                        @click="() => append(data)">
                        添加课程
                    </el-button>
                    <el-button 
                        type="text" 
                        size="mini" 
                        @click="edit(data)">
                        修改课程
                    </el-button>
                    <el-button
                        v-if="node.level == 2"
                        type="text"
                        size="mini"
                        @click="() => remove(node, data)">
                        删除课程
                    </el-button>
                    </span>
                </span>
            </el-tree>
        </div>

        <!-- 弹窗-->
        <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="30%"
        :close-on-click-modal="false"
        >
        <el-form :model="subject">
            <el-form-item label="课程名">
            <el-input v-model="subject.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="排序">
            <el-input v-model="subject.sort" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitData">确 定</el-button>
        </span>
        </el-dialog>

    </div>
</template>

<script>
import subject from '@/api/edu/subject.js';
  let id = 1000;

  export default {
    data() {
        return {
            filterText: '',
            data: [],
            defaultProps: {
            children: 'children',
            label: 'title'
            },
            subject:{
                id:null,
                title:"",
                parentId:0,
                sort:0,
            },
            //批量删除节点，因此需要一个集合
            pCid: [],
            // 拖拽后批量保存
            subjectList:[],
            // 是否开启拖拽
            draggable: false,
            // 更新的菜单节点
            updateNodes: [],
            // 当前拖拽的子节点深度（几级节点）
            maxLevel: 0,
            // 弹窗标题
            title: "",
            // 添加或更新
            dialogType: "", // edit,add
            // false不显示弹窗，true显示弹窗
            dialogVisible: false,
            // 默认展开菜单，用的是node-key="catId"
            expandedKey: [],
        }
    },

    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    methods: {
        //初始化方法
        init(){
            this.expandedKey = this.pCid;
            this.pCid = [];
            this.subject = {
                id:null,
                title:"",
                parentId:0,
                sort:0,
            };
            subject.getTree().then(response=>{
                console.log("data",response.data);
                this.data = response.data.data;
            })
        },
        //拖拽完保存
        batchSave(){
            console.log(this.subjectList);
            subject.updateSubject(this.subjectList).
            then(response=>{
                this.init();
                this.$message({
                    type:"success",
                    message:"批量更新成功"
                })
            })
        },
        // 批量删除
        batchDelete(){
            // 删除批量删除id的集合
            var ids = [];
            
            let checkedNodes = this.$refs.tree.getCheckedNodes();
            if(checkedNodes!=null&&checkedNodes.length>0){
                for(let i = 0;i<checkedNodes.length;i++){
                    ids.push(checkedNodes[i].id);
                    //展开该节点
                    if(this.pCid.indexOf(checkedNodes[i].parentId)==-1){
                        this.pCid.push(checkedNodes[i].parentId);
                    }
                }
                this.$confirm('此操作将永久删除该课程, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    subject.deleteSubject(ids).then(response=>{
                        this.init();
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    })
                }).catch(() => {});
            }
        },
        // 是否允许拖拽的方法，return true：允许、false：拒接
        allowDrop(draggingNode, dropNode, type) {
            console.log("allowDrop:", draggingNode, dropNode, type);
            let parentId = draggingNode.parentId;

            if(type == "inner"){
                if((draggingNode.childNodes==null||draggingNode.childNodes.length==0)&&dropNode.level == 1){
                    return true;
                }
            }else if(type =="next" ||type == "prev"){
                let level1 = draggingNode.level;
                let level2 = dropNode.level;
                console.log(level1,level2);
                if(level1 == 1 && level2 ==2 ){
                    return false;
                }
                return true;
            }
            return false;

        },
        // 拖拽成功后的方法
        handleDrop(draggingNode, dropNode, dropType, ev) {
            console.log("handleDrop:", draggingNode, dropNode, dropType);
            // this.subjectList 
            // 父节点的子节点 
            let subjects = dropNode.parent.childNodes;
            for(let i = 0;i<subjects.length;i++){
                subjects[i].data.sort = i+1;
                
                if(draggingNode.data.id == subjects[i].data.id){
                    // 拖拽的节点
                    subjects[i].data.parentId = dropNode.parent.data.id;
                }
                this.subjectList.push(subjects[i].data);
            }
            this.pCid.push(this.subjectList[this.subjectList.length-1].parentId);
        },
        //保存弹窗内容
        submitData(){
            let subjects = [];
            subjects.push(this.subject);
            (this.title=="添加课程"?subject.saveSubject(this.subject):subject.updateSubject(subjects)).
            then(response=>{
                // 关闭弹窗
                this.dialogVisible = false;
                this.init();
                this.$message({
                    type:"success",
                    message:response.data.message
                })
            })
        },
        // 将节点名字过滤成 -》小写 
        filterNode(value, data) {
            if (!value) return true
            return data.title.toLowerCase().indexOf(value.toLowerCase()) !== -1
        },
        //追加子节点
        append(data) {
            console.log("append", data);
            // 设置为添加数据，不是更新数据
            this.dialogType = "add";
            this.title = "添加课程";
            // 显示弹窗
            this.dialogVisible = true;
            this.subject.parentId = data.id;
            //展开该节点
            this.pCid.push(data.id);
        },
        //更新
        edit(data){
            console.log("edit", data);
            // 设置为添加数据，不是更新数据
            this.dialogType = "add";
            this.title = "修改课程";
            // 显示弹窗
            this.dialogVisible = true;
            subject.info(data.id).

            then(response=>{
                console.log("info",response);
                this.subject = response.data.info;
                //展开该节点
                this.pCid.push(data.id);
            })
        },
        //删除子节点
        remove(node, data) {
            console.log("delete",node,data);
            var ids = [];
            ids.push(data.id);
            this.$confirm('此操作将永久删除该课程, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                subject.deleteSubject(ids).then(response=>{
                    //展开该节点
                    this.pCid.push(data.parentId);
                    this.init();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                })
            }).catch(() => {});
            
        },
    },
    created(){
        this.init();
    }
  };
</script>
</script>

<style scoped>
 .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>